#!/bin/bash

# Set the directory where the backgrounds are stored
BACKGROUND_DIR="$HOME/.config/backgrounds"
CURRENT_BACKGROUND_FILE="$HOME/.config/hypr/env/.current_background"

# Get the list of backgrounds
BACKGROUND_LIST=("$BACKGROUND_DIR"/*)

# Prepare the background list for yad --list
backgrounds_string=$(printf "%s\n" "${BACKGROUND_LIST[@]}")

# Use Yad to display the list of backgrounds with a preview
selected_background=$(echo "$backgrounds_string" | yad --list --title="Select a Background" \
  --column="Backgrounds" --image-column="Preview:IMG" --separator=" " --height=400 --width=600 \
  --button=Cancel:1 --button=Apply:0 --item-icon "${BACKGROUND_LIST[@]}" --image-on-top)

# Capture the exit status of Yad
response=$?

# If the user clicks Cancel (exit status 1), exit the script
if [ $response -eq 1 ]; then
  exit 1
fi

# Trim any leading/trailing spaces and remove any extra formatting
selected_background=$(echo "$selected_background" | sed 's/|.*//')

# If no background is selected, exit
if [ -z "$selected_background" ]; then
  exit 1
fi

# Set the selected background and save it to the current background file
echo "$selected_background" > "$CURRENT_BACKGROUND_FILE"

# Apply the selected background using swww
swww img $selected_background --transition-type grow --transition-fps 120 --transition-pos 'top-right' --transition-duration 2

# Send a notification with the new background name and an icon from the current background
notify-send -i $selected_background "Background changed" "$(basename "$selected_background")"

